package com.ssb.util.sign;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;

/**
 * @author: Don
 * @date: 2018/9/4 19:05
 * @description:
 */
public class HttpUtil {
    /**
     * Discription 键-值格式发送post请求
     * @author Don
     * @date 2018/9/5 9:32
     * @param
     * @return
     */
    public static String sendKeyValuePost(String url, Map<String, String> headers, Map<String, String> params)
    {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try
        {
            //HttpClientContext context = HttpClientContext.create();
            HttpPost httpPost = new HttpPost(url);
            if(null != headers) {
                for (String name : headers.keySet()) {
                    httpPost.setHeader(name, headers.get(name));
                }
            }

            if(null != params) {
                List<NameValuePair> nvps = new ArrayList<>();
                for (String name : params.keySet()) {
                    nvps.add(new BasicNameValuePair(name, params.get(name)));
                }
                httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
            }
            CloseableHttpResponse response = httpClient.execute(httpPost);
            response.setLocale(Locale.CHINESE);
            try {
                HttpEntity entity = response.getEntity();
                String resposeStr = EntityUtils.toString(entity, "UTF-8");
                System.out.println("获取结果:" + resposeStr);
                return resposeStr;
            }
            finally {
                response.close();
            }
        }
        catch (UnsupportedEncodingException usex){
            //自己处理
            return null;
        }
        catch (ClientProtocolException cpex){
            //自己处理
            return null;
        }
        catch (Exception ex)
        {
            //自己处理
            return null;
        }
        finally {
            // 关闭连接,释放资源
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}
